#!/bin/python
# coding: utf-8

import os
import re
import time
from datetime import datetime

#REG = "^[ ]*([0-9]{2}-[0-9]{2}-[0-9]{4})[ ]*(.*)[ ]+([0-9])+[ ]+([-.0-9,]+)"
REG = "^([0-9]{2}-[0-9]{2}-[0-9]{4})[^ ]*(.*)[0-9,]*$"

class KbItem:
    price = 0
    var_symbol = 0
    date = None
    account = None
    info = None
    description = None

    #def __unicode__(self):
    #    return "%s %s" % (self.price, self.info)

class KbParser:
    items = []

    def __init__(self, path=None, path_dir=None):
        if path_dir:
    		files = os.listdir(path)
        	for item in files:
		    	self.parsefile(("%s/%s") % (path, item))
        if path:
		    self.parsefile( path )

    def parseLine( self, line ):
        if not re.match(REG, line.strip()) :
            return 

        array = [ it for it in line.split("   ") if it.strip() ]
        date = array[0]
        price = float ( array[-1].strip().replace(".", "").replace(",", ".") )

        oKb = KbItem()
        oKb.var_symbol = None
        oKb.price = price
        oKb.info =  array[1]
        oKb.description = "\t".join( array[2:-1] )
        oKb.date = datetime.fromtimestamp(time.mktime(time.strptime(date, "%d-%m-%Y"))).date()

        return oKb
    
    def parsefile(self,file_path):
        f = open(file_path, 'r')
        line = True

        # skip head
        while( line ):
            line = f.readline()
            if line.startswith("________"):
                break;

        read_next = False
        for line in f.readlines():
            if read_next:
                item = self.parseLine(line)
                if item:
                    self.items.append( item )

            if line.startswith("________"):
                read_next= True
            else:   
                read_next= False

    def getAll(self):
        return self.items

